package com.intellif.datasource;

import com.mongodb.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author by mozping
 * @Classname MongodbConnectionInit
 * @Description TODO
 * @Date 2019/4/17 10:04
 */

@Component
public class MongodbConnectionInit {



    @Autowired
    private MongoDbProperties mongoProperties;

    @Bean
    public MongoClient mongoClient() {

        MongoCredential createCredential = MongoCredential.createCredential(mongoProperties.getUsername(),
                mongoProperties.getDatabase(),
                mongoProperties.getPassword().toCharArray());
        MongoClientOptions options = MongoClientOptions.builder()
                //.writeConcern(WriteConcern.JOURNALED)
                //.writeConcern(WriteConcern.ACKNOWLEDGED)
                .writeConcern(WriteConcern.UNACKNOWLEDGED)
                .minConnectionsPerHost(mongoProperties.getMinConnectionsPerHost())
                .connectionsPerHost(mongoProperties.getConnectionsPerHost())
                .threadsAllowedToBlockForConnectionMultiplier(50)
                .maxWaitTime(60000)
                .connectTimeout(5000)
                .readConcern(ReadConcern.DEFAULT)
                .readPreference(ReadPreference.primaryPreferred())
                .build();
        List<ServerAddress> serverAddresses = new ArrayList<>();
        ArrayList<Integer> portList = mongoProperties.getPorts();
        for (String host : mongoProperties.getHosts()) {
            int index = mongoProperties.getHosts().indexOf(host);
            Integer port;
            if (portList != null && portList.size() == 1) {
                port = mongoProperties.getPorts().get(0);
            } else {
                port = mongoProperties.getPorts().get(index);
            }
            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }
        MongoClient client = new MongoClient(serverAddresses, Collections.singletonList(createCredential), options);
        return client;
    }

}
